use axum_app_common::model::PageResult;
use axum_app_macro::QueryPageBuilder;
use sea_orm::{
    sea_query::Expr, ColumnTrait, Condition, ConnectionTrait, EntityTrait, Order, PaginatorTrait,
    QueryFilter, QueryOrder, Set,
};
use tracing::error;

use crate::entity::{
    rbac_user_role_rel,
    rbac_user_role_rel::{Column, Entity, Model},
};

/**
 * 查询条件
 */
impl RbacUserRoleRelQueryCondition {
    pub fn user_id_eq(mut self, user_id: Option<&str>) -> Self {
        self.filter = self.filter.add_option(
            user_id
                .filter(|s| s.trim().len() > 0)
                .map(|s| Expr::col(rbac_user_role_rel::Column::UserId).eq(s)),
        );
        self
    }
}

#[derive(Debug, QueryPageBuilder)]
pub struct RbacUserRoleRelQuery;

impl RbacUserRoleRelQuery {
    pub async fn query_by_user_id<C>(
        db: &C,
        user_id: &str,
    ) -> anyhow::Result<Vec<rbac_user_role_rel::Model>>
    where
        C: ConnectionTrait,
    {
        let list = rbac_user_role_rel::Entity::find()
            .filter(Column::UserId.eq(user_id))
            .order_by_asc(Column::Id)
            .all(db)
            .await?;

        Ok(list)
    }
}

pub async fn insert<C>(db: &C, user_id: &str, role_code: &str) -> anyhow::Result<u64>
where
    C: ConnectionTrait,
{
    let model = rbac_user_role_rel::ActiveModel {
        user_id: sea_orm::ActiveValue::Set(user_id.to_string()),
        role_code: sea_orm::ActiveValue::Set(role_code.to_string()),
        ..Default::default()
    };

    let res = rbac_user_role_rel::Entity::insert(model).exec(db).await?;
    Ok(res.last_insert_id as u64)
}
